﻿using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;

namespace LeanEngine.Data.Linq.Language
{
    public sealed class SelectToken : IQueryToken
    {
        #region Constructor Members

        public SelectToken()
        {
            this.ColumnList = new List<ColumnToken>();
        }

        #endregion

        #region PropertyInfo Members

        public List<ColumnToken> ColumnList { get; set; }

        public bool Distinct { get; set; }

        public bool Count { get; set; }

        public int PageIndex { get; set; }

        public int PageSize { get; set; }

        #endregion

        #region ILanguageToken Members

        public string GetStatement()
        {
            var sql = new StringBuilder();
            sql.Append("SELECT ");
            if (this.Distinct) sql.Append("DISTINCT ");
            foreach (var column in this.ColumnList)
            {
                var columnList = column.GetStatement().Split('|');
                for (int i = 0; i < columnList.Length; i++)
                {
                    if (i > 0)
                    {
                        sql.Append(", ");
                        sql.Append(column.Table.Alias);
                        sql.Append(".");
                    }

                    sql.Append(columnList[i]);
                    sql.Append(" ");
                    sql.Append(column.Table.Name);
                    sql.Append("_");
                    sql.Append(columnList[i].Split('.').Last());
                }

                if (this.ColumnList.Last() != column)
                {
                    sql.Append(", ");
                }
            }

            return sql.ToString();
        }

        #endregion
    }
}
